﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ComponentModel;
using ProxyViewModel.Commands;
using System.Windows.Input;
namespace ProxyViewModel.Tests {
	[TestClass]
	public class ProxyCommandManagerAndInvalidator {

		public class TestViewModelA {
			public virtual string TestProperty {
				get;
				set;
			}
		}

		public class TestViewModelB {
			public void TestCommand() {

			}

			public bool CanExecuteTestCommand() {
				return true;
			}
		}

		[TestMethod]
		public void TestScenario1() {
			TestViewModelA viewModelA = ProxyViewModelFactory.CreateProxyViewModel<TestViewModelA>();
			TestViewModelB viewModelB = ProxyViewModelFactory.CreateProxyViewModel<TestViewModelB>();

			bool canExecuteCalled = false;

			((ICommand)viewModelB.GetType().GetProperty("Test").GetValue(viewModelB, null)).CanExecuteChanged += (s, e) => {
				canExecuteCalled = true;
			};

			viewModelA.TestProperty = "This is a test property";
			Assert.IsFalse(canExecuteCalled);
			ProxyCommandManager.RegisterCommandsInvalidator(viewModelA, viewModelB);

			viewModelA.TestProperty = "One more time";

			Assert.IsTrue(canExecuteCalled);
			canExecuteCalled = false;

			ProxyCommandManager.UnregisterCommandsInvalidator(viewModelA, viewModelB);
			Assert.IsFalse(canExecuteCalled);
		}

		[TestMethod]
		public void TestCannoRegisterUnregisterMultipleTimes() {
			TestViewModelA viewModelA = ProxyViewModelFactory.CreateProxyViewModel<TestViewModelA>();
			TestViewModelB viewModelB = ProxyViewModelFactory.CreateProxyViewModel<TestViewModelB>();

			bool canExecuteCalled = false;

			((ICommand)viewModelB.GetType().GetProperty("Test").GetValue(viewModelB, null)).CanExecuteChanged += (s, e) => {
				canExecuteCalled = true;
			};

			viewModelA.TestProperty = "This is a test property";
			Assert.IsFalse(canExecuteCalled);
			ProxyCommandManager.RegisterCommandsInvalidator(viewModelA, viewModelB);
			ProxyCommandManager.RegisterCommandsInvalidator(viewModelA, viewModelB);
			ProxyCommandManager.RegisterCommandsInvalidator(viewModelA, viewModelB);



			viewModelA.TestProperty = "One more time";

			Assert.IsTrue(canExecuteCalled);
			canExecuteCalled = false;

			ProxyCommandManager.UnregisterCommandsInvalidator(viewModelA, viewModelB);
			ProxyCommandManager.UnregisterCommandsInvalidator(viewModelA, viewModelB);
			ProxyCommandManager.UnregisterCommandsInvalidator(viewModelA, viewModelB);
			Assert.IsFalse(canExecuteCalled);
		}
	}
}
